﻿using FPC.Offer.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace FPC.Offer.UI.Base
{
    public class BasePage : System.Web.UI.Page
    {
        //菜单ID默认为0
        int _moduleID = 0;

        /// <summary>
        /// 的菜单ＩＤ（如果当前页面是子页面，此时的菜单ID是主页面的菜单ID）
        /// </summary>
        public int MenuID { get { return _moduleID; } set { _moduleID = value; } }

        /// <summary>
        /// 当前登录ID
        /// </summary>
        public int AccountID { get { return Session[SystemKeys.COOKIE_USER_UserID_REMEMBER] != null ? Convert.ToInt32(Session[SystemKeys.COOKIE_USER_UserID_REMEMBER]) : 0; } }
        /// <summary>
        /// 当前登录用户所属派出所(账户)
        /// </summary>
        public string Organize { get { return Session[SystemKeys.COOKIE_USER_OrganizeName_REMEMBER] != null ? Session[SystemKeys.COOKIE_USER_OrganizeName_REMEMBER].ToString() : ""; } }
        /// <summary>
        /// 当前登录用户名(账户)
        /// </summary>
        public string Account { get { return Session[SystemKeys.COOKIE_USER_NAME_REMEMBER] != null ? Session[SystemKeys.COOKIE_USER_NAME_REMEMBER].ToString() : ""; } }
        /// <summary>
        /// 当前登录用户角色权限
        /// </summary>
        public string Role_Right
        {
            get
            {
                //获取角色权限  
                FPC.Offer.UI.GeneralProcessor.Login.UserLogin rr = new FPC.Offer.UI.GeneralProcessor.Login.UserLogin();
                int Roleid = Convert.ToInt32(Session[SystemKeys.COOKIE_USER_ROLE_REMEMBER]);
                return rr.Role_Roght_Show(Roleid);
            }
        }

        #region 页面加载 权限判定
        /// <summary>页面加载前检查用户是否合法</summary>
        /// <param name="e">页面参数</param>
        /// <summary>
        protected void Page_Unload(object sender, EventArgs e)
        {
        }
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            //base.StartProcessRequest();
            if (AccountID == 0 || string.IsNullOrEmpty(Account))
            {
                //这里写 跳转到登陆页面
                System.Web.Security.FormsAuthentication.SignOut();
                System.Web.HttpContext.Current.Session.Abandon();
                Response.Redirect(string.Format("~/MainAndLogin/Login.aspx?action=loginout&Page={0}", Request.Path));
            }
            else
            {
                // 获取Url
                Uri oldUrl = Request.UrlReferrer;
                Uri newUrl = Request.Url;
                string AllRight = "";
                for (int i = 0; i < newUrl.Segments.Length; i++)
                {
                    if (newUrl.Segments[i].ToString().IndexOf("aspx") > 0)
                    {
                        AllRight = newUrl.Segments[i].ToString();
                    }
                }
                if (AllRight != "Deflaut.aspx" && AllRight != "Welcome.aspx" && AllRight != "Login.aspx")
                {
                string menu = HttpContext.Current.Request.QueryString["MenuID"];
                MenuID = string.IsNullOrEmpty(menu) ? 0 : int.Parse(menu);
                if (MenuID == 0)
                {
                    //得到要请求的页面的包含指定URL路径段的数组
                    string[] Segments = newUrl.Segments;
                    //获取数组最后一位的是RUL访问页面
                    string page = Segments[Segments.Length - 1];

                    //通过数组获取页面访问的绝对路径， 不包含文件名
                    string path = string.Empty;
                    for (int i = 1; i < Segments.Length - 1; i++)
                    {
                        path += Segments[i];
                    }
                    if (!Check_Permission(page, path))
                    {
                        //LogHelp.Info(string.Format("访问未经授权页面:{0}  已被拦截", HttpContext.Current.Request.Url));
                        throw new HttpException(401, "您要访问的页面不存在！");
                    }
                }
                else
                {
                    if (!Check_Permission("", ""))
                    {
                        //LogHelp.Info(string.Format("访问未经授权页面:{0}  已被拦截", HttpContext.Current.Request.Url));
                        throw new HttpException(401, "您要访问的页面不存在！");
                    }
                }
            }
        }
        }
        /// <summary>
        /// 检测权限
        /// </summary>
        private bool Check_Permission(string page, string path)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (!string.IsNullOrEmpty(page) && !string.IsNullOrEmpty(path))
                {
                    //受保护资源的扩展名         
                    List<String> protectedFiles = new List<string>();
                    protectedFiles.AddRange(new string[] { ".aspx", ".asmx", ".ashx" });
                    string found = protectedFiles.Find(s => page.ToLower().EndsWith(s));
                    if (found == null)
                        return false;
                    int ModID = 0;
                    bool isMod = new FPC.Offer.Service.System_RoleRightService().GetIsRoleRight(Session[FPC.Offer.Common.SystemKeys.COOKIE_USER_ROLE_REMEMBER].ToString(), page, ref ModID);
                    if (isMod)
                    {
                        MenuID = ModID;
                        return true;
                    }
                    return true;
                }
                else
                {
                    return new FPC.Offer.Service.System_RoleRightService().GetIsRoleRight(Session[FPC.Offer.Common.SystemKeys.COOKIE_USER_ROLE_REMEMBER].ToString(), MenuID);
                }
            }
            return false;
        }
        #endregion
    }
}